package com.mini.rpc.provider.registry.loadbalancer;

import com.mini.rpc.common.ServiceMeta;
import com.mini.rpc.provider.registry.exception.NoAvailableProviderException;

import java.util.List;
import java.util.Random;

/**
 * 负载均衡随机算法
 *
 * @author: hliushi
 * @date: 2022/4/24 9:29
 **/
public class RandomLoadBalancer implements ServiceLoadBalancer<ServiceMeta> {
    private final Random random = new Random();

    /**
     * 随机获取实例
     *
     * @param servers  服务节点列表
     * @param hashCode 客服端节点的hashCode
     * @return 服务节点实例
     */
    @Override
    public ServiceMeta select(List<ServiceMeta> servers, int hashCode) {
        if (servers.size() == 0) {
            throw new NoAvailableProviderException("no available provider");
        }
        return servers.get(random.nextInt(servers.size()));
    }
}
